package com.tgy.twodatabaseplus.kafka;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

/***
 * @ClassName: MyConsumer
 * @Description:
 * @Auther: 送你一块二向箔
 * @Date: 14:53 2022/4/2
 * @version : V1.0
 */
@Component
@Slf4j
public class MyConsumer {
    public static void main(String[] args) {
        resver();
    }
    private final static String TOPIC_NAME = "yaml";
    private final static String CONSUMER_GROUP_NAME = "bbb";


    public static void resver(){
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");
        // 消费分组名
        props.put(ConsumerConfig.GROUP_ID_CONFIG, CONSUMER_GROUP_NAME);
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        //创建一个消费者的客户端
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String,String>(props);
        // 消费者订阅主题列表
        //consumer.subscribe(Arrays.asList(TOPIC_NAME));
        //指定分区消费
        consumer.assign(Arrays.asList(new TopicPartition(TOPIC_NAME, 0 )));
        //消息回溯消费
        consumer.seekToBeginning(Arrays.asList(new TopicPartition(TOPIC_NAME,0 )));
        log.debug("这是一条测试debug =============================");
        log.info("这是一条测试info =============================");
        log.error("这是一条测试error =============================");

        while (true) {
            /*
             * poll() API 是拉取消息的⻓轮询
             */
            ConsumerRecords<String, String> records =consumer.poll(Duration.ofMillis( 1000 ));
            for (ConsumerRecord<String, String> record : records) {
                System.out.printf("收到消息：partition = %d,offset = %d, key =%s, value = %s%n", record.partition(),record.offset(), record.key(), record.value());
            }
        }
    }
}
